#!/usr/bin/env bash

### BEGIN ###
# Author: idevz
# Since: 2018/03/12
# Description:       Set up LORMP development environment.
# ./init.sh          Set up using $(pwd) as BASE_DIR, download and install PHP, OpenResy.
#
# Environment variables that control init:
# PV: php version which you want to install.
# http://jp2.php.net/distributions/php-7.2.11.tar.gz
### END ###

set -e

[ -z $PRLCTL_HOME ] && PRLCTL_HOME=/media/psf/runX
[ $HOME != '/home/z' ] && echo 'Are U Z ?' && exit 1

BASE_DIR=${BASE_DIR:-$(dirname $(cd $(dirname "$0") && pwd -P)/$(basename "$0"))}

PHP_VERSION=${PV:-"php-7.2.11"}
PHP_ROOT=${LR:-"/usr/local/${PHP_VERSION}"}

install_php_from_src() {
	sudo yum install -y openssl-devel curl-devel
	[ -d ${PHP_ROOT} ] && sudo rm -rf ${PHP_ROOT}

	PHP_SRC="http://jp2.php.net/distributions/${PHP_VERSION}.tar.gz"
	PHP_SRC_ROOT=${BASE_DIR}/srcs
	[ ! -f ${PHP_SRC_ROOT}/${PHP_VERSION}.tar.gz ] &&
		curl -fSL ${PHP_SRC} -o ${PHP_SRC_ROOT}/${PHP_VERSION}.tar.gz

	[ -d ${PHP_SRC_ROOT}/${PHP_VERSION} ] && sudo rm -rf ${PHP_SRC_ROOT}/${PHP_VERSION}

	cd ${PHP_SRC_ROOT} &&
		tar zxf ${PHP_VERSION}.tar.gz &&
		cd ${PHP_VERSION} &&
		./configure --prefix=${PHP_ROOT} --enable-phpdbg --enable-phpdbg-debug \
			--enable-phpdbg-webhelper --enable-debug --enable-fpm --with-mysqli --with-zlib \
			--enable-mbstring=all --with-iconv-dir=/usr/local/idevz --enable-sockets --with-pear \
			--enable-ftp --with-libxml-dir --with-mcrypt --with-pdo-mysql --with-freetype-dir \
			--with-jpeg-dir --with-png-dir --with-gd --enable-gd-native-ttf --enable-pcntl \
			--with-curl --enable-soap --with-gdbm --with-libdir=lib64 --with-openssl --enable-shmop \
			--enable-sysvsem --enable-sysvshm --enable-sysvmsg &&
		make -j4 &&
		sudo make install
}

PROFILE=$(
	cat <<EOF
#!/usr/bin/env bash

### BEGIN ###
# Author: idevz
# Since: 2018/03/12
# Description:       Setting enviroment variables for lormp pvm.
### END ###

export PHP_ROOT=${PHP_ROOT}
export PATH=${PHP_ROOT}/bin:${PHP_ROOT}/sbin:\$PATH

EOF
)

install_or() {
	OLD_BASE_DIR=${BASE_DIR}
	OLD_PROFILE=${PROFILE}

	BASE_DIR=${PRLCTL_HOME}/deploy/openresty && . "${BASE_DIR}/init"
	yum_base_preparing
	or_for_debug
	install_test_nginx
	install_luarocks
	create_profile "${PROFILE}" "openresty"

	BASE_DIR=${OLD_BASE_DIR}
	PROFILE=${OLD_PROFILE}
}

init() {
	install_or
	install_php_from_src
	create_profile "${PROFILE}"
}
